namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    using System.Web;

    /// <summary>
    /// 1.	Start at Workplace homepage
    /// 2.	Select Reports from Left Pane
    /// 3.	Select Campaign Comparison. (Double Click)
    /// 4.  Click Run Report
    /// 5.  Select a campaign from left drop down
    /// 6.  select another campaign from right drop down
    /// 7.	Click View Report
    /// </summary>

    public class CampaignComparisonReport : CrmWebTest
    {
        public void CampaignComparisonReport_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            er = new EntityRequest();
            er.Type = EntityNames.Reports;
            er.ParentID = new Guid(user["organizationid"]);
            er.ReturnAs = EntityNames.Reports;

            System.Collections.Hashtable reportProps = new System.Collections.Hashtable();
            reportProps.Add("filename", "Campaign Comparison.rdl");
            er.Props = reportProps;

            report = (CRMEntity)(EntityManager.Instance.GetEntities(er)[EntityNames.Reports]);
            EntityManager.Instance.FreeEntity(report);            
        }

        public void CampaignComparisonReport_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            EntityManager.Instance.FreeEntity(user);            
        }

        public CampaignComparisonReport()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());

            this.Proxy = null;
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CampaignComparisonReport_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CampaignComparisonReport_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("NavReportHomepage");

            CRMReports_home_reports_aspx reports = new CRMReports_home_reports_aspx(user);
            yield return (reports);

            this.EndTransaction("NavReportHomepage");

            this.BeginTransaction("OpenCampaignComparisonReport");

            crmreports_viewer_viewer_aspx viewer = new crmreports_viewer_viewer_aspx(user);
            viewer.id = new Guid(report["reportid"]);
            viewer.helpId = report["filename"];
            viewer.action = "filter";
            yield return (viewer);

            this.EndTransaction("OpenCampaignComparisonReport");

            this.BeginTransaction("CampaignComparisonReport");

            AdvancedFind.AdvancedFind af = new AdvancedFind.AdvancedFind();
            WebTestRequest wtr = null;

            try { af.GetDefaultAdvancedFindView("campaign", false); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);
            }
            yield return (wtr);

            wtr = null;
            try { af.GetEntityFieldList("campaign"); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            try { af.GetLinkedEntityList("campaign"); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);
                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            CRMReports_rsviewer_reportviewer_aspx rsviewer = new CRMReports_rsviewer_reportviewer_aspx(crmServer);
            rsviewer.id = new Guid(report["reportid"]);
            rsviewer.uniquename = user["organizationName"];
            rsviewer.isScheduledReport = false;
            string temp = "%3CReportFilter%3E%3CReportEntity+paramname%3D%22CRM_FilteredCampaign%22+displayname%3D%22Campaigns%22%3E%3Cfetch+version%3D%221.0%22+output-format%3D%22xml-platform%22+mapping%3D%22logical%22+distinct%3D%22false%22%3E%3Centity+name%3D%22campaign%22%3E%3Call-attributes%2F%3E%3C%2Fentity%3E%3C%2Ffetch%3E%0D%0A%3C%2FReportEntity%3E%3C%2FReportFilter%3E";
            temp = HttpUtility.UrlDecode(temp);
            rsviewer.CRM_filter = temp;
            yield return (rsviewer);

            int Idx = rsviewer.lastResponse.BodyString.IndexOf(idx1);
            string match = rsviewer.lastResponse.BodyString.Substring(Idx + 26);
            string __EVENTTARGET = match.Substring(0, match.IndexOf('"'));

            Idx = rsviewer.lastResponse.BodyString.IndexOf(idx2);
            match = rsviewer.lastResponse.BodyString.Substring(Idx + idx2.Length);
            string __EVENTARGUMENT = match.Substring(0, match.IndexOf('"'));

            Idx = rsviewer.lastResponse.BodyString.IndexOf(idx3);
            match = rsviewer.lastResponse.BodyString.Substring(Idx + idx3.Length);
            string __VIEWSTATE = match.Substring(0, match.IndexOf('"'));

            Idx = rsviewer.lastResponse.BodyString.IndexOf(idx4);
            match = rsviewer.lastResponse.BodyString.Substring(Idx + idx4.Length);
            string __EVENTVALIDATION = match.Substring(0, match.IndexOf('"'));            

            rsviewer = new CRMReports_rsviewer_reportviewer_aspx(crmServer);
            rsviewer.__EVENTTARGET = __EVENTTARGET;
            rsviewer.__EVENTARGUMENT = __EVENTARGUMENT;
            rsviewer.__VIEWSTATE = __VIEWSTATE;
            rsviewer.__EVENTVALIDATION = __EVENTVALIDATION;
            yield return (rsviewer);
            
            this.EndTransaction("CampaignComparisonReport");
        }

        private string idx1 = "id=\"__EVENTTARGET\" value=\"";
        private string idx2 = "id=\"__EVENTARGUMENT\" value=\"";
        private string idx3 = "id=\"__VIEWSTATE\" value=\"";
        private string idx4 = "id=\"__EVENTVALIDATION\" value=\"";
                
        private CRMEntity user;
        private CRMEntity report;
        private string crmServer;

        WRPCInfo rpcInfo;
        WebTestRequestHeader headerItem;
        private string tokenKey;
    }
}



